'use strict';
// npx sequelize migration:generate --name=<操作名称></操作名称>
// npx sequelize db:migrate
// npx sequelize db:migrate:undo

module.exports = {
  // 在执行数据库升级时调用的函数，创建 users 表
  up: async (queryInterface, Sequelize) => {
    const { INTEGER, DATE, STRING, BOOLEAN, TEXT } = Sequelize;

    // 角色表，角色组的描述
    await queryInterface.createTable('roles', {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      title: STRING(30),
      description: STRING(200),
      isAdmin: BOOLEAN,
      status: BOOLEAN,
      created_at: DATE,
      updated_at: DATE,
    });
    queryInterface.addIndex('roles', [ 'title' ], { unique: true });

    // 路由表，记录系统路由和对应的控制器
    await queryInterface.createTable('routers', {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      title: STRING(30),
      description: STRING(200),
      path: STRING(200),
      action_name: STRING(30),
      controller_name: STRING(200),
      middleware_name: STRING(200),
      status: BOOLEAN,
      created_at: DATE,
      updated_at: DATE,
    });
    queryInterface.addIndex('routers', [ 'path', 'title' ]);


    // 分配的访问表，定义系统资源，和路由表里对应
    await queryInterface.createTable('resources', {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      pid: INTEGER,
    //  router_name: STRING(30),
    //  controller_name: STRING(30),
      type: STRING(10), // 菜单menu，页面page，按键butto
    //  url: STRING(200),
      icon: STRING(30),
      router_id: INTEGER,
      sort: INTEGER,
      description: STRING(200),
      status: BOOLEAN,
      created_at: DATE,
      updated_at: DATE,
    });
    queryInterface.addIndex('resources', [ 'router_id', 'type' ]);

    // 角色权限表，角色有哪些权限。
    await queryInterface.createTable('roleresources', {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      resource_array: TEXT, // 资源ID 编号数组
      role_id: INTEGER,
      created_at: DATE,
      updated_at: DATE,
    });

    // await queryInterface.createTable('role_accesss', {
    //   id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    //   access_id: INTEGER,
    //   role_id: INTEGER,
    //   created_at: DATE,
    //   updated_at: DATE,
    // });
    // queryInterface.addIndex('role_accesss', [ 'access_id', 'role_id' ]);

  },
  // 在执行数据库降级时调用的函数，删除 users 表
  down: async queryInterface => {
    await queryInterface.dropTable('users');
    await queryInterface.dropTable('roles');
    await queryInterface.dropTable('routers');
    await queryInterface.dropTable('resources');
  //  await queryInterface.dropTable('role_accesss');
    await queryInterface.dropTable('roleresource');
  },
};
